package com.goldcn.user.service;

import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.config.ProConstants;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.user.dao.GoldSetingMapper;
import com.goldcn.user.model.GoldSeting;
import com.goldcn.util.DataUtils;
import com.goldcn.util.HttpUtil;
import com.goldcn.util.JsonUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author Tim Peng
 * mail: lmn_022@163.com
 * Date: 2017/8/8
 * Time: 15:34
 * To change this template use File | Settings | File Templates.
 */
@Service
@Transactional
public class GoldSetingService {

    @Autowired
    GoldSetingMapper goldSetingMapper;

    @Autowired
    RestTemplate restTemplate;

    public Object getGoldSetingByNecklace(Long supplierID,String name){
        return goldSetingMapper.getGoldSetingByNecklace(supplierID,name);
    }

    public List<GoldSeting> selectAllBySupplierID(Long supplierID){
        return  goldSetingMapper.selectAll(supplierID);
    }

    public Object update(GoldSeting goldSeting){
        goldSeting.setCompanyID(SystemContext.getCompanyID());
        goldSetingMapper.updateByPrimaryKeySelective(goldSeting);
        return "ok";
    }

    public Object searchGoldPriceByNecklace(Long supplierID,String name){
        GoldSeting goldSeting = goldSetingMapper.getGoldSetingByNecklace(supplierID,name);
        if (goldSeting.getIsGold()==1){
            //获取当日金价
            String url = ProConstants.getNowGoldPrice;
            if(name.equals("AG999")){
                url = url+"/AG999";
            }else if(name.equals("AU9999")){
                url = url+"/AU9999";
            }
            //获取实时金价
            DataResult result = HttpUtil.httpGet(url, restTemplate);
            if (result.getIsSuccess() == 0) {
                throw new ServiceException("调用point服务获取实时金价接口出错", RestConst.ErrorCode.SERVICE_FAIL);
            }
            BigDecimal price = new BigDecimal(result.getData().toString());
            return  price.add(goldSeting.getFloatPrice());
        }
        return null == goldSeting.getGoldPrice()?goldSeting.getFloatPrice():goldSeting.getFloatPrice().add(goldSeting.getGoldPrice());
    }
}
